/**
 * 企业舆情分析系统 - 前端应用
 * Microsoft Fluent Design风格
 */

// 全局变量
const API_BASE = '/api';
let dashboardCharts = {};
let currentSessionId = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 企业舆情分析系统前端启动');
    initializeApp();
    loadDashboard();
    loadProviders();
    setInterval(loadDashboard, 30000); // 30秒刷新一次
    
    // 初始化模态框增强功能
    initializeModalEnhancements();
});

// 模态框增强功能
function initializeModalEnhancements() {
    // ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeModal();
        }
    });
    
    // 点击模态框背景关闭
    document.addEventListener('click', function(event) {
        if (event.target.classList.contains('modal-overlay')) {
            closeModal();
        }
    });
    
    // 处理模态框焦点管理
    document.addEventListener('modalopen', function(event) {
        const modal = event.detail;
        const focusableElements = modal.querySelectorAll(
            'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
        );
        
        if (focusableElements.length > 0) {
            focusableElements[0].focus();
        }
        
        // 捕获Tab键循环
        modal.addEventListener('keydown', function(e) {
            if (e.key === 'Tab') {
                const firstElement = focusableElements[0];
                const lastElement = focusableElements[focusableElements.length - 1];
                
                if (e.shiftKey && document.activeElement === firstElement) {
                    e.preventDefault();
                    lastElement.focus();
                } else if (!e.shiftKey && document.activeElement === lastElement) {
                    e.preventDefault();
                    firstElement.focus();
                }
            }
        });
    });
}

// 初始化应用
function initializeApp() {
    fetch(`${API_BASE}/health`)
        .then(response => response.json())
        .then(data => {
            console.log('✅ 系统健康检查:', data);
            updateSystemStatus(data);
        })
        .catch(error => {
            console.error('❌ 系统健康检查失败:', error);
            showToast('系统连接失败，请检查后端服务', 'error');
        });
}

// 页面导航
function showPage(pageId) {
    // 特殊处理大屏跳转
    if (pageId === 'bigscreen') {
        window.open('./dashboard/index.html', '_blank');
        return;
    }
    
    // 隐藏所有页面
    document.querySelectorAll('.page-content').forEach(page => {
        page.classList.remove('active');
    });
    
    // 移除侧边栏活动状态
    document.querySelectorAll('.sidebar-menu a').forEach(link => {
        link.classList.remove('active');
    });
    
    // 显示目标页面
    const targetPage = document.getElementById(pageId);
    if (targetPage) {
        targetPage.classList.add('active');
    }
    
    // 激活对应的侧边栏链接
    const activeLink = document.querySelector(`[onclick="showPage('${pageId}')"]`);
    if (activeLink) {
        activeLink.classList.add('active');
    }
    
    // 根据页面加载对应数据
    switch(pageId) {
        case 'dashboard':
            loadDashboard();
            break;
        case 'sessions':
            loadSessions();
            break;
        case 'reports':
            loadReports();
            break;
        case 'projects':
            loadProjects();
            break;
        case 'threats':
            loadThreatStatistics();
            loadThreatSessionsForThreats();
            break;
        case 'alerts':
            loadThreatSessionsForDetails();
            break;
        case 'config':
            loadProviders();
            break;
        case 'threat-analysis':
            loadAvailableSessions();
            loadThreatSessions();
            break;
    }
}

// 加载数据大屏
async function loadDashboard() {
    try {
        const statsResponse = await fetch(`${API_BASE}/dashboard/stats`);
        const statsData = await statsResponse.json();
        
        if (statsData.success) {
            updateStatsCards(statsData.stats);
            updateTrendChart(statsData.daily_analysis);
            updateThreatChart(statsData.threat_distribution);
        }
    } catch (error) {
        console.error('❌ 加载数据大屏失败:', error);
    }
}

// 更新统计卡片
function updateStatsCards(stats) {
    document.getElementById('total-enterprises').textContent = stats.total_enterprises || 0;
    document.getElementById('total-sessions').textContent = stats.total_sessions || 0;
    document.getElementById('threat-sessions').textContent = stats.threat_sessions || 0;
    
    // 计算系统健康度
    const healthPercentage = Math.round((stats.successful_responses / (stats.total_responses || 1)) * 100);
    document.getElementById('system-health').textContent = `${healthPercentage}%`;
    
    animateNumbers();
}

// 更新趋势图表
function updateTrendChart(dailyData) {
    const chartDom = document.getElementById('trend-chart');
    if (!chartDom) return;
    
    if (!dashboardCharts.trend) {
        dashboardCharts.trend = echarts.init(chartDom);
    }
    
    const dates = dailyData.map(item => item.date.substring(5));
    const counts = dailyData.map(item => item.count);
    
    const option = {
        title: { text: '' },
        grid: { left: '10%', right: '10%', top: '10%', bottom: '20%' },
        xAxis: {
            type: 'category',
            data: dates,
            axisLabel: { color: '#605e5c', fontSize: 12 },
            axisLine: { lineStyle: { color: '#e1dfdd' } }
        },
        yAxis: {
            type: 'value',
            axisLabel: { color: '#605e5c', fontSize: 12 },
            axisLine: { lineStyle: { color: '#e1dfdd' } },
            splitLine: { lineStyle: { color: '#f3f2f1' } }
        },
        series: [{
            data: counts,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: { color: '#0078d4', width: 3 },
            itemStyle: { color: '#0078d4' },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0, y: 0, x2: 0, y2: 1,
                    colorStops: [
                        { offset: 0, color: 'rgba(0, 120, 212, 0.3)' },
                        { offset: 1, color: 'rgba(0, 120, 212, 0.05)' }
                    ]
                }
            }
        }]
    };
    
    dashboardCharts.trend.setOption(option);
}

// 更新威胁图表
function updateThreatChart(threatData) {
    const chartDom = document.getElementById('threat-chart');
    if (!chartDom) return;
    
    if (!dashboardCharts.threat) {
        dashboardCharts.threat = echarts.init(chartDom);
    }
    
    const data = threatData.map(item => ({
        name: item.level,
        value: item.count
    }));
    
    const option = {
        title: { text: '' },
        legend: {
            orient: 'vertical',
            left: 'left',
            textStyle: { color: '#605e5c' }
        },
        series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            data: data,
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            },
            itemStyle: {
                color: function(params) {
                    const colors = {
                        'low': '#107c10',
                        'medium': '#ffb900',
                        'high': '#d13438',
                        'critical': '#881798'
                    };
                    return colors[params.name] || '#0078d4';
                }
            }
        }]
    };
    
    dashboardCharts.threat.setOption(option);
}

// 开始企业分析
async function startAnalysis() {
    const enterpriseName = document.getElementById('enterprise-name').value.trim();
    if (!enterpriseName) {
        showToast('请输入企业名称', 'error');
        return;
    }
    
    const questionTypes = [];
    document.querySelectorAll('.checkbox-group input[type="checkbox"]:checked').forEach(checkbox => {
        questionTypes.push(checkbox.value);
    });
    
    if (questionTypes.length === 0) {
        showToast('请至少选择一种分析类型', 'warning');
        return;
    }
    
    const useInspiration = document.getElementById('use-inspiration').checked;
    
    const progressDiv = document.getElementById('analysis-progress');
    const resultDiv = document.getElementById('analysis-result');
    progressDiv.style.display = 'block';
    resultDiv.innerHTML = '';
    
    try {
        const response = await fetch(`${API_BASE}/analysis/enterprise`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                enterprise_name: enterpriseName,
                question_types: questionTypes,
                use_inspiration: useInspiration,
                max_questions_per_type: 3,
                min_total_questions: 30
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentSessionId = data.session_id;
            progressDiv.style.display = 'none';
            resultDiv.innerHTML = `
                <div class="card" style="border-left: 4px solid var(--success-color);">
                    <div class="card-body">
                        <h3 style="color: var(--success-color); margin-bottom: 8px;">
                            <i class="fas fa-check-circle"></i> 分析完成
                        </h3>
                        <p style="margin-bottom: 16px;">${data.message}</p>
                        <p style="color: var(--neutral-100); margin-bottom: 20px;">会话ID: ${data.session_id}</p>
                        <div style="display: flex; gap: 12px;">
                            ${data.threat_session_id ? `
                                <button class="btn btn-primary" onclick="viewThreatDetails('${data.threat_session_id}')">
                                    <i class="fas fa-shield-alt"></i> 查看威胁分析
                                </button>
                            ` : `
                                <button class="btn btn-warning" onclick="startThreatAnalysis('${data.session_id}')">
                                    <i class="fas fa-shield-alt"></i> 威胁分析
                                </button>
                            `}
                            <button class="btn btn-primary" onclick="viewSessionDetails('${data.session_id}')">
                                <i class="fas fa-eye"></i> 查看详情
                            </button>
                            <button class="btn btn-secondary" onclick="generateReport('${data.session_id}')">
                                <i class="fas fa-file-alt"></i> 生成报告
                            </button>
                        </div>
                    </div>
                </div>
            `;
            setTimeout(loadDashboard, 2000);
        } else {
            // 如果是系统未初始化错误，显示特殊处理
            if (data.error && data.error.includes('系统未初始化')) {
                showSystemInitError(data);
            } else {
                throw new Error(data.error || '分析失败');
            }
        }
    } catch (error) {
        console.error('❌ 企业分析失败:', error);
        progressDiv.style.display = 'none';
        resultDiv.innerHTML = `
            <div class="card" style="border-left: 4px solid var(--error-color);">
                <div class="card-body">
                    <h3 style="color: var(--error-color);">
                        <i class="fas fa-exclamation-triangle"></i> 分析失败
                    </h3>
                    <p>${error.message}</p>
                </div>
            </div>
        `;
    }
}

// 开始威胁分析
async function startThreatAnalysis(sessionId) {
    try {
        showToast('正在进行威胁分析...', 'info');
        
        const response = await fetch(`${API_BASE}/threat/analyze/${sessionId}`, {
            method: 'POST'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast(`威胁分析完成！威胁会话ID: ${data.threat_session_id}`, 'success');
            setTimeout(loadDashboard, 2000);
        } else {
            // 处理特定错误
            if (data.action_required === 'configure_deepseek') {
                showToast('威胁分析需要配置DeepSeek API Key，请在系统配置中设置', 'warning');
                // 可以选择性地跳转到配置页面
                showPage('settings');
                return;
            }
            throw new Error(data.error || '威胁分析失败');
        }
    } catch (error) {
        console.error('❌ 威胁分析失败:', error);
        showToast(`威胁分析失败: ${error.message}`, 'error');
    }
}

// 清空表单
function clearForm() {
    document.getElementById('enterprise-name').value = '';
    document.querySelectorAll('.checkbox-group input[type="checkbox"]').forEach(checkbox => {
        checkbox.checked = false;
    });
    // 默认选中一些重要的分析类型
    ['negative_news', 'positive_news', 'financial_info', 'market_competition', 'legal_compliance', 'risk_assessment'].forEach(id => {
        const checkbox = document.getElementById(id);
        if (checkbox) checkbox.checked = true;
    });
    document.getElementById('use-inspiration').checked = true;
    document.getElementById('analysis-result').innerHTML = '';
}

// 加载分析会话列表
async function loadSessions() {
    const loadingDiv = document.getElementById('sessions-loading');
    const listDiv = document.getElementById('sessions-list');
    
    loadingDiv.style.display = 'block';
    listDiv.innerHTML = '';
    
    try {
        const response = await fetch(`${API_BASE}/analysis/sessions?limit=50`);
        const data = await response.json();
        
        if (data.success) {
            loadingDiv.style.display = 'none';
            
            if (data.sessions.length === 0) {
                listDiv.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-inbox"></i>
                        <h3>暂无分析记录</h3>
                        <p>开始您的第一次企业分析</p>
                    </div>
                `;
                return;
            }
            
            listDiv.innerHTML = `
                <div class="list-group">
                    ${data.sessions.map(session => `
                        <div class="session-list-item">
                            <div class="session-main-content" onclick="viewSessionDetails('${session.session_id}')">
                                <div class="list-item-content">
                                    <div class="list-item-title">${session.enterprise_name}</div>
                                    <div class="list-item-subtitle">
                                        ${formatTime(session.created_at)} | 
                                        问题数: ${session.total_questions || 0} | 
                                        成功响应: ${session.successful_responses || 0}
                                    </div>
                                </div>
                                <div class="session-status">
                                    ${getStatusBadge(session.status)}
                                </div>
                            </div>
                            <div class="session-actions">
                                <button class="btn btn-sm btn-primary" onclick="event.stopPropagation(); viewSessionDetails('${session.session_id}')" title="查看详情">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-sm btn-secondary" onclick="event.stopPropagation(); generateReport('${session.session_id}')" title="生成报告">
                                    <i class="fas fa-file-export"></i>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="event.stopPropagation(); confirmDeleteSession('${session.session_id}')" title="删除会话">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `;
        } else {
            throw new Error(data.error || '加载失败');
        }
    } catch (error) {
        console.error('❌ 加载会话列表失败:', error);
        loadingDiv.style.display = 'none';
        listDiv.innerHTML = `
            <div class="card" style="border-left: 4px solid var(--error-color);">
                <div class="card-body">
                    <h3 style="color: var(--error-color);">加载失败</h3>
                    <p>${error.message}</p>
                </div>
            </div>
        `;
    }
}

// 加载历史报告
async function loadReports() {
    const loadingDiv = document.getElementById('reports-loading');
    const listDiv = document.getElementById('reports-list');
    
    loadingDiv.style.display = 'block';
    listDiv.innerHTML = '';
    
    try {
        const response = await fetch(`${API_BASE}/reports`);
        const data = await response.json();
        
        if (data.success) {
            loadingDiv.style.display = 'none';
            
            if (data.reports.length === 0) {
                listDiv.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-file-alt"></i>
                        <h3>暂无报告</h3>
                        <p>完成企业分析后即可生成报告</p>
                    </div>
                `;
                return;
            }
            
            listDiv.innerHTML = `
                <div class="grid grid-2">
                    ${data.reports.map(report => `
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-building"></i>
                                    ${report.enterprise_name}
                                </h3>
                                <div class="badge badge-info">${report.type === 'enterprise_analysis' ? '企业分析' : report.type || '报告'}</div>
                            </div>
                            <div class="card-body">
                                <p style="color: var(--neutral-100); margin-bottom: 16px;">
                                    ${formatTime(report.created_at)}
                                </p>
                                <div style="display: flex; gap: 8px;">
                                    <button class="btn btn-primary" onclick="viewReport('${report.id}')">
                                        <i class="fas fa-eye"></i> 查看
                                    </button>
                                    <button class="btn btn-secondary" onclick="downloadReport('${report.id}')">
                                        <i class="fas fa-download"></i> 下载
                                    </button>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `;
        } else {
            throw new Error(data.error || '加载失败');
        }
    } catch (error) {
        console.error('❌ 加载报告列表失败:', error);
        loadingDiv.style.display = 'none';
        listDiv.innerHTML = `
            <div class="card" style="border-left: 4px solid var(--error-color);">
                <div class="card-body">
                    <h3 style="color: var(--error-color);">加载失败</h3>
                    <p>${error.message}</p>
                </div>
            </div>
        `;
    }
}

// 加载项目管理
async function loadProjects() {
    const gridDiv = document.getElementById('projects-grid');
    
    try {
        const response = await fetch(`${API_BASE}/projects`);
        const data = await response.json();
        
        if (data.success) {
            if (data.projects.length === 0) {
                gridDiv.innerHTML = `
                    <div class="empty-state" style="grid-column: 1 / -1;">
                        <i class="fas fa-folder"></i>
                        <h3>暂无项目</h3>
                        <p>创建您的第一个项目来管理分析数据</p>
                    </div>
                `;
                return;
            }
            
            gridDiv.innerHTML = data.projects.map(project => `
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-folder"></i>
                            ${project.name}
                        </h3>
                    </div>
                    <div class="card-body">
                        <p style="color: var(--neutral-100); margin-bottom: 16px;">
                            ${project.description || '暂无描述'}
                        </p>
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                            <span style="color: var(--neutral-100);">分析会话</span>
                            <span style="font-weight: 600;">${project.session_count || 0}</span>
                        </div>
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                            <span style="color: var(--neutral-100);">已完成</span>
                            <span style="font-weight: 600;">${project.completed_count || 0}</span>
                        </div>
                        <div style="display: flex; gap: 8px;">
                            <button class="btn btn-primary" onclick="viewProject('${project.id}')">
                                <i class="fas fa-eye"></i> 查看
                            </button>
                            <button class="btn btn-secondary" onclick="editProject('${project.id}')">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
        } else {
            throw new Error(data.error || '加载失败');
        }
    } catch (error) {
        console.error('❌ 加载项目失败:', error);
        gridDiv.innerHTML = `
            <div class="card" style="border-left: 4px solid var(--error-color); grid-column: 1 / -1;">
                <div class="card-body">
                    <h3 style="color: var(--error-color);">加载失败</h3>
                    <p>${error.message}</p>
                </div>
            </div>
        `;
    }
}

// 创建项目
async function createProject() {
    const name = document.getElementById('project-name').value.trim();
    const description = document.getElementById('project-description').value.trim();
    
    if (!name) {
        showToast('请输入项目名称', 'warning');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/projects`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name, description })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast('项目创建成功', 'success');
            document.getElementById('project-name').value = '';
            document.getElementById('project-description').value = '';
            loadProjects();
        } else {
            throw new Error(data.error || '创建失败');
        }
    } catch (error) {
        console.error('❌ 创建项目失败:', error);
        showToast(`创建失败: ${error.message}`, 'error');
    }
}

// 加载AI提供商配置
async function loadProviders() {
    try {
        const response = await fetch(`${API_BASE}/config/providers`);
        const data = await response.json();
        
        if (data.providers) {
            updateProvidersUI(data.providers);
        }
    } catch (error) {
        console.error('❌ 加载提供商配置失败:', error);
    }
}

// 更新提供商UI
function updateProvidersUI(providers) {
    const container = document.getElementById('providers-container');
    
    const providerNames = {
        'baidu': '百度ERNIE',
        'aliyun': '阿里云通义千问',
        'zhipu': '智谱GLM',
        'kimi': 'Kimi',
        'deepseek': 'DeepSeek'
    };
    
    container.innerHTML = Object.entries(providers).map(([key, config]) => `
        <div class="card" style="margin-bottom: 20px;">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-robot"></i>
                    ${providerNames[key] || key}
                </h3>
                <div class="badge ${config.enabled ? 'badge-success' : 'badge-error'}">
                    ${config.enabled ? '已启用' : '未启用'}
                </div>
            </div>
            <div class="card-body">
                <div class="form-group">
                    <label class="form-label">API Key</label>
                    <input type="password" id="${key}-api-key" class="form-input" 
                           value="${config.api_key || ''}" placeholder="请输入API Key">
                </div>
                
                ${key === 'baidu' ? `
                    <div class="form-group">
                        <label class="form-label">Secret Key</label>
                        <input type="password" id="${key}-secret-key" class="form-input" 
                               value="${config.secret_key || ''}" placeholder="请输入Secret Key">
                    </div>
                ` : ''}
                
                <div class="form-group">
                    <div class="checkbox-item">
                        <input type="checkbox" id="${key}-enabled" ${config.enabled ? 'checked' : ''}>
                        <label for="${key}-enabled">启用此服务</label>
                    </div>
                </div>
                
                <button class="btn btn-primary" onclick="updateProvider('${key}')">
                    <i class="fas fa-save"></i> 保存配置
                </button>
            </div>
        </div>
    `).join('');
}

// 更新提供商配置
async function updateProvider(provider) {
    try {
        const apiKey = document.getElementById(`${provider}-api-key`).value.trim();
        const enabled = document.getElementById(`${provider}-enabled`).checked;
        
        const config = { api_key: apiKey, enabled: enabled };
        
        if (provider === 'baidu') {
            const secretKey = document.getElementById(`${provider}-secret-key`).value.trim();
            config.secret_key = secretKey;
        }
        
        const response = await fetch(`${API_BASE}/config/providers/${provider}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(config)
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast(data.message, 'success');
            setTimeout(loadProviders, 1000);
        } else {
            throw new Error(data.error || '更新失败');
        }
    } catch (error) {
        console.error('❌ 更新提供商配置失败:', error);
        showToast(`更新失败: ${error.message}`, 'error');
    }
}

// 初始化系统数据库
async function initializeSystem() {
    try {
        showToast('正在初始化系统数据库...', 'info');
        
        const response = await fetch(`${API_BASE}/system/initialize`, {
            method: 'POST'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast(data.message, 'success');
        } else {
            throw new Error(data.error || '初始化失败');
        }
    } catch (error) {
        console.error('❌ 系统初始化失败:', error);
        showToast(`初始化失败: ${error.message}`, 'error');
    }
}

// 测试连接
async function testConnection() {
    try {
        showToast('正在测试系统连接...', 'info');
        
        const response = await fetch(`${API_BASE}/health`);
        const data = await response.json();
        
        if (data.status === 'healthy') {
            showToast('系统连接正常！', 'success');
        } else {
            throw new Error('系统状态异常');
        }
    } catch (error) {
        console.error('❌ 连接测试失败:', error);
        showToast(`连接测试失败: ${error.message}`, 'error');
    }
}

// 显示Toast通知
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        ${message}
        <button onclick="this.parentElement.remove()" 
                style="float: right; background: none; border: none; color: inherit; 
                       font-size: 18px; cursor: pointer; margin-left: 10px;">&times;</button>
    `;
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        if (toast.parentElement) {
            toast.remove();
        }
    }, 3000);
}

// 格式化时间
function formatTime(timeString) {
    const date = new Date(timeString);
    const now = new Date();
    const diff = now - date;
    
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    
    return date.toLocaleDateString('zh-CN');
}

// 获取状态徽章
function getStatusBadge(status) {
    const statusMap = {
        'running': '<span class="status-badge running">运行中</span>',
        'completed': '<span class="status-badge completed">已完成</span>',
        'error': '<span class="status-badge error">错误</span>',
        'cancelled': '<span class="status-badge cancelled">已取消</span>'
    };
    return statusMap[status] || `<span class="status-badge">${status}</span>`;
}

// 数字动画效果
function animateNumbers() {
    const numbers = document.querySelectorAll('.stat-number');
    numbers.forEach(num => {
        const target = parseInt(num.textContent) || 0;
        let current = 0;
        const increment = target / 30;
        
        const animate = () => {
            current += increment;
            if (current < target) {
                num.textContent = Math.floor(current);
                requestAnimationFrame(animate);
            } else {
                num.textContent = target;
            }
        };
        
        animate();
    });
}

// 更新系统状态
function updateSystemStatus(healthData) {
    // 可以在这里更新系统状态显示
    console.log('系统状态更新:', healthData);
}

// 窗口大小改变时重新调整图表
window.addEventListener('resize', () => {
    Object.values(dashboardCharts).forEach(chart => {
        if (chart && chart.resize) {
            chart.resize();
        }
    });
});

// 占位符函数，避免JavaScript错误
// 查看会话详情
async function viewSessionDetails(sessionId) {
    try {
        const response = await fetch(`${API_BASE}/analysis/sessions/${sessionId}`);
        const data = await response.json();
        
        if (data.success) {
            // 创建模态框显示详情
            const modal = document.createElement('div');
            modal.className = 'modal-overlay';
            modal.innerHTML = `
                <div class="modal-content" style="max-width: 900px; max-height: 85vh; overflow-y: auto;">
                    <div class="modal-header">
                        <h2>
                            <i class="fas fa-file-alt"></i>
                            分析会话详情
                        </h2>
                        <button class="btn-close" onclick="closeModal()">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="session-overview">
                            <div class="info-grid">
                                <div class="info-item">
                                    <label>会话ID</label>
                                    <span>${data.session.session_id}</span>
                                </div>
                                <div class="info-item">
                                    <label>企业名称</label>
                                    <span>${data.session.enterprise_name}</span>
                                </div>
                                <div class="info-item">
                                    <label>创建时间</label>
                                    <span>${formatTime(data.session.created_at)}</span>
                                </div>
                                <div class="info-item">
                                    <label>状态</label>
                                    <span>${getStatusBadge(data.session.status)}</span>
                                </div>
                                <div class="info-item">
                                    <label>问题总数</label>
                                    <span>${data.session.total_questions || 0}</span>
                                </div>
                                <div class="info-item">
                                    <label>成功响应</label>
                                    <span>${data.session.successful_responses || 0}</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="session-actions" style="margin: 20px 0; text-align: center;">
                            <button class="btn btn-primary" onclick="generateReport('${sessionId}')">
                                <i class="fas fa-file-export"></i>
                                生成报告
                            </button>
                            <button class="btn btn-warning" onclick="confirmDeleteSession('${sessionId}')">
                                <i class="fas fa-trash"></i>
                                删除会话
                            </button>
                        </div>
                        
                        <div class="questions-section" style="margin-top: 24px;">
                            <h3>
                                <i class="fas fa-question-circle"></i>
                                问题和回答详情
                            </h3>
                            ${data.questions && data.questions.length > 0 ? data.questions.map((q, index) => `
                                <div class="question-card" style="margin-bottom: 20px;">
                                    <div class="card">
                                        <div class="card-header">
                                            <div class="question-header">
                                                <span class="question-number">#${index + 1}</span>
                                                <span class="question-type-badge">${q.question_type}</span>
                                                ${q.is_inspirational ? '<span class="badge inspirational-badge">启发式</span>' : ''}
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="question-text">
                                                <h4>问题:</h4>
                                                <p>${q.question_text}</p>
                                            </div>
                                            <div class="responses-section">
                                                <h4>AI响应:</h4>
                                                ${q.responses && Object.keys(q.responses).length > 0 ? 
                                                    Object.entries(q.responses).map(([provider, resp]) => `
                                                        <div class="response-item ${resp.success ? 'success' : 'error'}">
                                                            <div class="response-header">
                                                                <strong class="provider-name">${provider}</strong>
                                                                <div class="response-meta">
                                                                    <span class="response-status ${resp.success ? 'success' : 'error'}">
                                                                        ${resp.success ? '✅ 成功' : '❌ 失败'}
                                                                    </span>
                                                                    ${resp.response_time ? `<span class="response-time">${resp.response_time}ms</span>` : ''}
                                                                </div>
                                                            </div>
                                                            <div class="response-content">
                                                                ${resp.success ? 
                                                                    `<p>${resp.text}</p>` : 
                                                                    `<p class="error-message">错误: ${resp.error_message || '未知错误'}</p>`
                                                                }
                                                            </div>
                                                        </div>
                                                    `).join('') : 
                                                    '<p class="no-responses">暂无AI响应</p>'
                                                }
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `).join('') : '<div class="empty-state"><p>暂无问题数据</p></div>'}
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        } else {
            showToast(`获取会话详情失败: ${data.error}`, 'error');
        }
    } catch (error) {
        console.error('❌ 查看会话详情失败:', error);
        showToast('查看会话详情失败', 'error');
    }
}

// 确认删除会话
function confirmDeleteSession(sessionId) {
    const modal = document.createElement('div');
    modal.className = 'modal-overlay';
    modal.innerHTML = `
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header">
                <h2 style="color: var(--error-color);">
                    <i class="fas fa-exclamation-triangle"></i>
                    确认删除
                </h2>
                <button class="btn-close" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个分析会话吗？</p>
                <p style="color: var(--error-color); font-size: 14px;">此操作不可撤销，将删除所有相关的问题和响应数据。</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
                <button class="btn btn-danger" onclick="deleteSession('${sessionId}')">
                    <i class="fas fa-trash"></i>
                    确认删除
                </button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

// 删除会话
async function deleteSession(sessionId) {
    try {
        const response = await fetch(`${API_BASE}/analysis/sessions/${sessionId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast('会话删除成功', 'success');
            closeModal(); // 关闭确认对话框
            closeModal(); // 关闭详情对话框
            loadSessions(); // 刷新会话列表
        } else {
            showToast(`删除失败: ${data.error}`, 'error');
        }
    } catch (error) {
        console.error('❌ 删除会话失败:', error);
        showToast('删除会话失败', 'error');
    }
}

// 生成报告
async function generateReport(sessionId) {
    try {
        showToast('正在生成报告...', 'info');
        // 这里可以添加报告生成逻辑
        setTimeout(() => {
            showToast('报告生成完成', 'success');
            loadReports(); // 刷新报告列表
        }, 2000);
    } catch (error) {
        console.error('❌ 生成报告失败:', error);
        showToast('生成报告失败', 'error');
    }
}

// 查看报告
async function viewReport(reportId) {
    try {
        const response = await fetch(`${API_BASE}/reports/${reportId}`);
        const data = await response.json();
        
        if (data.success) {
            // 创建模态框显示报告
            const modal = document.createElement('div');
            modal.className = 'modal-overlay';
            modal.innerHTML = `
                <div class="modal-content" style="max-width: 900px; max-height: 80vh; overflow-y: auto;">
                    <div class="modal-header">
                        <h2>${data.report.enterprise_name} - 分析报告</h2>
                        <button class="btn-close" onclick="this.parentElement.parentElement.parentElement.remove()">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="info-grid" style="margin-bottom: 20px;">
                            <div><strong>企业名称:</strong> ${data.report.enterprise_name}</div>
                            <div><strong>分析时间:</strong> ${formatTime(data.report.created_at)}</div>
                            <div><strong>状态:</strong> ${getStatusBadge(data.report.status)}</div>
                            <div><strong>问题总数:</strong> ${data.report.total_questions}</div>
                        </div>
                        
                        ${data.report.threat_analysis ? `
                            <div class="card" style="margin-bottom: 20px;">
                                <div class="card-header">
                                    <h3>威胁分析概要</h3>
                                </div>
                                <div class="card-body">
                                    <div style="display: flex; gap: 16px;">
                                        <div class="stat-item">
                                            <div class="stat-value" style="color: var(--error-color);">${data.report.threat_analysis.risk_counts.high}</div>
                                            <div class="stat-label">高风险</div>
                                        </div>
                                        <div class="stat-item">
                                            <div class="stat-value" style="color: var(--warning-color);">${data.report.threat_analysis.risk_counts.medium}</div>
                                            <div class="stat-label">中风险</div>
                                        </div>
                                        <div class="stat-item">
                                            <div class="stat-value" style="color: var(--success-color);">${data.report.threat_analysis.risk_counts.low}</div>
                                            <div class="stat-label">低风险</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ` : ''}
                        
                        <div>
                            <h3>详细分析结果</h3>
                            ${Object.entries(data.report.questions || {}).map(([type, q]) => `
                                <div class="card" style="margin-bottom: 16px;">
                                    <div class="card-header">
                                        <strong>${type}</strong>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>问题:</strong> ${q.question}</p>
                                        ${Object.entries(q.responses || {}).map(([provider, resp]) => `
                                            <div style="margin-top: 12px; padding: 12px; background: var(--neutral-10); border-radius: 8px;">
                                                <strong>${provider}:</strong>
                                                <p style="margin-top: 8px;">${resp.text}</p>
                                                <small style="color: var(--neutral-100);">响应时间: ${resp.response_time}ms</small>
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-primary" onclick="downloadReport('${reportId}')">
                            <i class="fas fa-download"></i> 下载报告
                        </button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        } else {
            showToast('获取报告详情失败', 'error');
        }
    } catch (error) {
        console.error('❌ 查看报告失败:', error);
        showToast('查看报告失败', 'error');
    }
}

// 下载报告
async function downloadReport(reportId) {
    try {
        const response = await fetch(`${API_BASE}/reports/${reportId}`);
        const data = await response.json();
        
        if (data.success) {
            // 生成报告内容
            const reportContent = generateReportContent(data.report);
            
            // 创建下载链接
            const blob = new Blob([reportContent], { type: 'text/plain;charset=utf-8' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${data.report.enterprise_name}-分析报告-${new Date().toISOString().split('T')[0]}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            
            showToast('报告下载完成', 'success');
        } else {
            showToast('下载报告失败', 'error');
        }
    } catch (error) {
        console.error('❌ 下载报告失败:', error);
        showToast('下载报告失败', 'error');
    }
}

// 生成报告内容
function generateReportContent(report) {
    let content = `企业舆情分析报告\n`;
    content += `================================\n\n`;
    content += `企业名称: ${report.enterprise_name}\n`;
    content += `分析时间: ${formatTime(report.created_at)}\n`;
    content += `分析状态: ${report.status}\n`;
    content += `问题总数: ${report.total_questions}\n\n`;
    
    if (report.threat_analysis) {
        content += `威胁分析概要:\n`;
        content += `- 高风险: ${report.threat_analysis.risk_counts.high}\n`;
        content += `- 中风险: ${report.threat_analysis.risk_counts.medium}\n`;
        content += `- 低风险: ${report.threat_analysis.risk_counts.low}\n\n`;
    }
    
    content += `详细分析结果:\n`;
    content += `================================\n\n`;
    
    Object.entries(report.questions || {}).forEach(([type, q]) => {
        content += `问题类型: ${type}\n`;
        content += `问题内容: ${q.question}\n\n`;
        
        Object.entries(q.responses || {}).forEach(([provider, resp]) => {
            content += `${provider} 回答:\n`;
            content += `${resp.text}\n`;
            content += `响应时间: ${resp.response_time}ms\n\n`;
        });
        
        content += `--------------------------------\n\n`;
    });
    
    return content;
}

// 批量导出报告
async function exportAllReports() {
    try {
        showToast('正在导出所有报告...', 'info');
        const response = await fetch(`${API_BASE}/reports`);
        const data = await response.json();
        
        if (data.success && data.reports.length > 0) {
            // 生成批量报告
            let allContent = `企业舆情分析 - 批量报告\n`;
            allContent += `生成时间: ${new Date().toLocaleString()}\n`;
            allContent += `报告总数: ${data.reports.length}\n\n`;
            allContent += `================================\n\n`;
            
            for (let report of data.reports) {
                allContent += `企业: ${report.enterprise_name}\n`;
                allContent += `时间: ${formatTime(report.created_at)}\n`;
                allContent += `状态: ${report.status}\n`;
                allContent += `问题数: ${report.total_questions}\n`;
                allContent += `提供商数: ${report.provider_count}\n\n`;
            }
            
            // 下载文件
            const blob = new Blob([allContent], { type: 'text/plain;charset=utf-8' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `企业舆情分析-批量报告-${new Date().toISOString().split('T')[0]}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            
            showToast('批量导出完成', 'success');
        } else {
            showToast('没有可导出的报告', 'warning');
        }
    } catch (error) {
        console.error('❌ 批量导出失败:', error);
        showToast('批量导出失败', 'error');
    }
}

// 查看项目
async function viewProject(projectId) {
    try {
        const response = await fetch(`${API_BASE}/projects/${projectId}`);
        const data = await response.json();
        
        if (data.success) {
            // 创建模态框显示项目详情
            const modal = document.createElement('div');
            modal.className = 'modal-overlay';
            modal.innerHTML = `
                <div class="modal-content" style="max-width: 1000px; max-height: 85vh; overflow-y: auto;">
                    <div class="modal-header">
                        <h2>
                            <i class="fas fa-folder-open"></i>
                            项目详情 - ${data.project.name}
                        </h2>
                        <button class="btn-close" onclick="closeModal()">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="project-overview">
                            <div class="info-grid">
                                <div class="info-item">
                                    <label>项目ID</label>
                                    <span>${data.project.id}</span>
                                </div>
                                <div class="info-item">
                                    <label>企业名称</label>
                                    <span>${data.project.name}</span>
                                </div>
                                <div class="info-item">
                                    <label>分析会话数</label>
                                    <span>${data.project.sessions?.length || 0}</span>
                                </div>
                                <div class="info-item">
                                    <label>威胁分析数</label>
                                    <span>${data.project.threat_sessions?.length || 0}</span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 会话列表 -->
                        <div class="project-section">
                            <h3>
                                <i class="fas fa-history"></i>
                                分析会话列表
                            </h3>
                            ${data.project.sessions && data.project.sessions.length > 0 ? `
                                <div class="sessions-grid">
                                    ${data.project.sessions.map(session => `
                                        <div class="session-card">
                                            <div class="session-card-header">
                                                <div class="session-id">${session.session_id.substring(0, 8)}...</div>
                                                <div class="session-status">${getStatusBadge(session.status)}</div>
                                            </div>
                                            <div class="session-card-body">
                                                <div class="session-info">
                                                    <div class="info-row">
                                                        <span class="label">创建时间:</span>
                                                        <span class="value">${formatTime(session.created_at)}</span>
                                                    </div>
                                                    <div class="info-row">
                                                        <span class="label">问题数:</span>
                                                        <span class="value">${session.total_questions || 0}</span>
                                                    </div>
                                                </div>
                                                <div class="session-actions">
                                                    <button class="btn btn-sm btn-primary" onclick="viewSessionDetails('${session.session_id}')">
                                                        <i class="fas fa-eye"></i> 查看详情
                                                    </button>
                                                    <button class="btn btn-sm btn-secondary" onclick="generateReport('${session.session_id}')">
                                                        <i class="fas fa-file-export"></i> 生成报告
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    `).join('')}
                                </div>
                            ` : '<div class="empty-state"><p>暂无分析会话</p></div>'}
                        </div>
                        
                        <!-- 威胁分析列表 -->
                        ${data.project.threat_sessions && data.project.threat_sessions.length > 0 ? `
                            <div class="project-section">
                                <h3>
                                    <i class="fas fa-shield-alt"></i>
                                    威胁分析列表
                                </h3>
                                <div class="threat-sessions-grid">
                                    ${data.project.threat_sessions.map(threat => `
                                        <div class="threat-session-card">
                                            <div class="threat-card-header">
                                                <div class="threat-id">${threat.analysis_session_id?.substring(0, 8)}...</div>
                                                <div class="threat-count">${threat.threats_detected || 0} 威胁</div>
                                            </div>
                                            <div class="threat-card-body">
                                                                                                 <div class="threat-info">
                                                     <div class="info-row">
                                                         <span class="label">分析时间:</span>
                                                         <span class="value">${formatTime(threat.analysis_started_at)}</span>
                                                     </div>
                                                 </div>
                                                <div class="threat-actions">
                                                    <button class="btn btn-sm btn-warning" onclick="viewThreatDetails('${threat.analysis_session_id}')">
                                                        <i class="fas fa-exclamation-triangle"></i> 查看威胁
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        ` : ''}
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        } else {
            showToast(`获取项目详情失败: ${data.error}`, 'error');
        }
    } catch (error) {
        console.error('❌ 查看项目失败:', error);
        showToast('查看项目失败', 'error');
    }
}

// 编辑项目
function editProject(projectId) {
    // 创建编辑模态框
    const modal = document.createElement('div');
    modal.className = 'modal-overlay';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h2>编辑项目</h2>
                <button class="btn-close" onclick="this.parentElement.parentElement.parentElement.remove()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>项目名称</label>
                    <input type="text" id="edit-project-name" class="form-control" placeholder="输入项目名称">
                </div>
                <div class="form-group">
                    <label>项目描述</label>
                    <textarea id="edit-project-description" class="form-control" placeholder="输入项目描述"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="this.parentElement.parentElement.parentElement.remove()">取消</button>
                <button class="btn btn-primary" onclick="saveProjectEdit('${projectId}')">保存</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

// 保存项目编辑
async function saveProjectEdit(projectId) {
    const name = document.getElementById('edit-project-name').value.trim();
    const description = document.getElementById('edit-project-description').value.trim();
    
    if (!name) {
        showToast('请输入项目名称', 'warning');
        return;
    }
    
    try {
        showToast('正在保存...', 'info');
        // 这里添加实际的保存逻辑
        setTimeout(() => {
            showToast('项目更新成功', 'success');
            document.querySelector('.modal-overlay').remove();
            loadProjects();
        }, 1000);
    } catch (error) {
        console.error('❌ 保存项目失败:', error);
        showToast('保存项目失败', 'error');
    }
}

// 导出配置
async function exportConfig() {
    try {
        const response = await fetch(`${API_BASE}/config/providers`);
        const data = await response.json();
        
        if (data.providers) {
            // 移除敏感信息
            const exportData = {};
            Object.entries(data.providers).forEach(([key, config]) => {
                exportData[key] = {
                    enabled: config.enabled,
                    // 不导出API密钥
                };
            });
            
            const configContent = JSON.stringify(exportData, null, 2);
            const blob = new Blob([configContent], { type: 'application/json' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `config-export-${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            
            showToast('配置导出完成', 'success');
        } else {
            showToast('导出配置失败', 'error');
        }
    } catch (error) {
        console.error('❌ 导出配置失败:', error);
        showToast('导出配置失败', 'error');
    }
}

// 显示系统初始化错误信息
function showSystemInitError(data) {
    const modal = document.createElement('div');
    modal.className = 'modal-overlay';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h2 style="color: var(--error-color);">
                    <i class="fas fa-exclamation-triangle"></i>
                    系统未初始化
                </h2>
                <button class="btn-close" onclick="this.parentElement.parentElement.parentElement.remove()">&times;</button>
            </div>
            <div class="modal-body">
                <p style="margin-bottom: 16px;">${data.error}</p>
                ${data.suggestion ? `<p style="margin-bottom: 16px; color: var(--info-color);"><strong>建议:</strong> ${data.suggestion}</p>` : ''}
                <div class="card" style="margin-bottom: 16px; background: var(--warning-bg);">
                    <div class="card-body">
                        <h4>解决步骤:</h4>
                        <ol style="margin-left: 20px;">
                            <li>前往"系统配置"页面</li>
                            <li>配置至少一个AI服务提供商的API Key</li>
                            <li>点击"保存配置"</li>
                            <li>重新尝试分析</li>
                        </ol>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="this.parentElement.parentElement.parentElement.remove()">关闭</button>
                <button class="btn btn-primary" onclick="showPage('config'); this.parentElement.parentElement.parentElement.remove();">
                    <i class="fas fa-cog"></i> 前往配置
                </button>
                <button class="btn btn-info" onclick="reinitializeSystem()">
                    <i class="fas fa-sync"></i> 重新初始化
                </button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

// 重新初始化系统
async function reinitializeSystem() {
    try {
        showToast('正在重新初始化系统...', 'info');
        
        const response = await fetch(`${API_BASE}/system/reinit`, {
            method: 'POST'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showToast(`系统初始化成功！已启用 ${data.provider_count} 个AI服务`, 'success');
            // 关闭错误模态框
            const modal = document.querySelector('.modal-overlay');
            if (modal) modal.remove();
        } else {
            showToast('系统初始化失败，请检查配置', 'error');
        }
    } catch (error) {
        console.error('❌ 重新初始化失败:', error);
        showToast('重新初始化失败', 'error');
    }
}

// 检查系统状态
async function checkSystemStatus() {
    try {
        const response = await fetch(`${API_BASE}/system/status`);
        const data = await response.json();
        
        if (data.success) {
            const status = data.status;
            console.log('系统状态:', status);
            
            // 更新UI显示系统状态
            updateSystemStatusUI(status);
            
            if (!status.ready_for_analysis) {
                showToast('系统尚未准备就绪，请配置AI服务', 'warning');
            }
        }
    } catch (error) {
        console.error('❌ 获取系统状态失败:', error);
    }
}

// 更新系统状态UI
function updateSystemStatusUI(status) {
    // 在仪表板页面更新系统状态信息
    const statusElement = document.getElementById('system-status');
    if (statusElement) {
        const readyText = status.ready_for_analysis ? 
            '<span style="color: var(--success-color);">✅ 系统就绪</span>' : 
            '<span style="color: var(--warning-color);">⚠️ 需要配置</span>';
        
        statusElement.innerHTML = `
            <div class="card">
                <div class="card-header">
                    <h3>系统状态</h3>
                </div>
                <div class="card-body">
                    <p><strong>总体状态:</strong> ${readyText}</p>
                    <p><strong>已启用AI服务:</strong> ${status.providers.total_enabled} / ${status.providers.total_configured}</p>
                    <p><strong>分析系统:</strong> ${status.systems.analysis ? '✅ 正常' : '❌ 异常'}</p>
                    <p><strong>威胁系统:</strong> ${status.systems.threat ? '✅ 正常' : '❌ 异常'}</p>
                    <p><strong>数据库:</strong> ${status.systems.database ? '✅ 正常' : '❌ 异常'}</p>
                </div>
            </div>
        `;
    }
}

// ==================== 威胁分析功能 ====================

// 加载可用的分析会话
async function loadAvailableSessions() {
    try {
        const response = await fetch(`${API_BASE}/analysis/sessions?limit=100`);
        const data = await response.json();
        
        if (data.success) {
            const select = document.getElementById('session-select');
            select.innerHTML = '<option value="">请选择一个分析会话</option>';
            
            data.sessions.forEach(session => {
                const option = document.createElement('option');
                option.value = session.session_id;
                option.textContent = `${session.enterprise_name} - ${formatTime(session.created_at)} (${session.session_id})`;
                select.appendChild(option);
            });
            
            showToast('会话列表已更新', 'success');
        } else {
            showToast('加载会话列表失败', 'error');
        }
    } catch (error) {
        console.error('❌ 加载会话列表失败:', error);
        showToast('加载会话列表失败', 'error');
    }
}

// 开始手动威胁分析
async function startManualThreatAnalysis() {
    const selectedSessionId = document.getElementById('session-select').value;
    const manualSessionId = document.getElementById('manual-session-id').value.trim();
    
    const sessionId = selectedSessionId || manualSessionId;
    
    if (!sessionId) {
        showToast('请选择或输入一个会话ID', 'warning');
        return;
    }
    
    const progressDiv = document.getElementById('threat-analysis-progress');
    const resultDiv = document.getElementById('threat-analysis-result');
    
    progressDiv.style.display = 'block';
    resultDiv.innerHTML = '';
    
    try {
        const response = await fetch(`${API_BASE}/threat/analyze/${sessionId}`, {
            method: 'POST'
        });
        
        const data = await response.json();
        progressDiv.style.display = 'none';
        
        if (data.success) {
            resultDiv.innerHTML = `
                <div class="card" style="border-left: 4px solid var(--success-color);">
                    <div class="card-body">
                        <h3 style="color: var(--success-color); margin-bottom: 8px;">
                            <i class="fas fa-check-circle"></i> 威胁分析完成
                        </h3>
                        <p style="margin-bottom: 16px;">${data.message}</p>
                        <p style="color: var(--neutral-100); margin-bottom: 20px;">威胁会话ID: ${data.threat_session_id}</p>
                        <div style="display: flex; gap: 12px;">
                            <button class="btn btn-primary" onclick="viewThreatDetails('${data.threat_session_id}')">
                                <i class="fas fa-eye"></i> 查看威胁详情
                            </button>
                            <button class="btn btn-secondary" onclick="downloadThreatReport('${data.threat_session_id}')">
                                <i class="fas fa-file-alt"></i> 下载报告
                            </button>
                        </div>
                    </div>
                </div>
            `;
            loadThreatSessions(); // 刷新威胁分析历史列表
            showToast('威胁分析完成', 'success');
        } else {
            if (data.action_required === 'configure_deepseek') {
                resultDiv.innerHTML = `
                    <div class="card" style="border-left: 4px solid var(--warning-color);">
                        <div class="card-body">
                            <h3 style="color: var(--warning-color);">
                                <i class="fas fa-exclamation-triangle"></i> 需要配置DeepSeek API Key
                            </h3>
                            <p>威胁分析需要DeepSeek API Key，请先在系统配置中设置。</p>
                            <button class="btn btn-primary" onclick="showPage('config')">
                                <i class="fas fa-cog"></i> 前往配置
                            </button>
                        </div>
                    </div>
                `;
                showToast('需要配置DeepSeek API Key', 'warning');
            } else {
                throw new Error(data.error || '威胁分析失败');
            }
        }
    } catch (error) {
        console.error('❌ 手动威胁分析失败:', error);
        progressDiv.style.display = 'none';
        resultDiv.innerHTML = `
            <div class="card" style="border-left: 4px solid var(--error-color);">
                <div class="card-body">
                    <h3 style="color: var(--error-color);">
                        <i class="fas fa-exclamation-triangle"></i> 威胁分析失败
                    </h3>
                    <p>${error.message}</p>
                </div>
            </div>
        `;
        showToast(`威胁分析失败: ${error.message}`, 'error');
    }
}

// 加载威胁分析会话列表
async function loadThreatSessions() {
    const loadingDiv = document.getElementById('threat-sessions-loading');
    const listDiv = document.getElementById('threat-sessions-list');
    
    loadingDiv.style.display = 'block';
    listDiv.innerHTML = '';
    
    try {
        const response = await fetch(`${API_BASE}/threats?limit=20`);
        const data = await response.json();
        
        if (data.success) {
            loadingDiv.style.display = 'none';
            
            if (data.threat_sessions.length === 0) {
                listDiv.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-shield-alt"></i>
                        <h3>暂无威胁分析记录</h3>
                        <p>开始您的第一次威胁分析</p>
                    </div>
                `;
                return;
            }
            
            listDiv.innerHTML = data.threat_sessions.map(session => `
                <div class="card session-card" style="margin-bottom: 16px;">
                    <div class="card-body">
                        <div class="session-header">
                            <h3 class="session-title">${session.enterprise_name}</h3>
                            <div class="session-meta">
                                <span class="session-id">威胁ID: ${session.analysis_session_id}</span>
                                <span class="session-date">${formatTime(session.analysis_started_at)}</span>
                            </div>
                        </div>
                        <div class="session-stats">
                            <div class="stat-item">
                                <span class="stat-label">分析响应</span>
                                <span class="stat-value">${session.total_responses}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">检测威胁</span>
                                <span class="stat-value">${session.threats_detected}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">威胁等级</span>
                                <span class="stat-value threat-level-${session.highest_threat_level}">${getThreatLevelText(session.highest_threat_level)}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">状态</span>
                                <span class="stat-value">${getStatusBadge(session.status)}</span>
                            </div>
                        </div>
                        <div class="session-actions">
                            <button class="btn btn-primary btn-sm" onclick="viewThreatDetails('${session.analysis_session_id}')">
                                <i class="fas fa-eye"></i> 查看详情
                            </button>
                            <button class="btn btn-secondary btn-sm" onclick="downloadThreatReport('${session.analysis_session_id}')">
                                <i class="fas fa-download"></i> 下载报告
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
        } else {
            loadingDiv.style.display = 'none';
            listDiv.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-exclamation-triangle"></i>
                    <h3>加载失败</h3>
                    <p>${data.error}</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('❌ 加载威胁分析会话失败:', error);
        loadingDiv.style.display = 'none';
        listDiv.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-exclamation-triangle"></i>
                <h3>加载失败</h3>
                <p>无法连接到服务器</p>
            </div>
        `;
    }
}

// 获取威胁等级文本
function getThreatLevelText(level) {
    const levelMap = {
        'critical': '严重',
        'high': '高危',
        'medium': '中危',
        'low': '低危'
    };
    return levelMap[level] || level;
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'running': '运行中',
        'completed': '已完成',
        'error': '错误',
        'cancelled': '已取消',
        'pending': '等待中',
        'analyzing': '分析中'
    };
    return statusMap[status] || status;
}

// 关闭模态窗口（增强版）
function closeModal() {
    const modals = document.querySelectorAll('.modal-overlay');
    modals.forEach(modal => {
        // 添加淡出动画
        modal.style.animation = 'modalFadeOut 0.15s ease-in';
        const modalContent = modal.querySelector('.modal-content');
        if (modalContent) {
            modalContent.style.animation = 'modalSlideOut 0.15s ease-in';
        }
        
        // 延迟移除以显示动画
        setTimeout(() => {
            modal.remove();
        }, 150);
    });
    
    // 恢复页面焦点到触发元素
    if (window.lastFocusedElement) {
        window.lastFocusedElement.focus();
        window.lastFocusedElement = null;
    }
}

// 下载文件通用函数
function downloadFile(filename, content) {
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}

// 查看威胁详情
function viewThreatDetails(analysisSessionId) {
    // 跳转到威胁详情管理页面并选择对应会话
    showPage('alerts');
    
    // 延迟一下确保页面已加载
    setTimeout(async () => {
        try {
            // 先加载威胁会话列表
            await loadThreatSessionsForDetails();
            
            // 设置选中的会话
            const selector = document.getElementById('threat-session-selector');
            if (selector) {
                selector.value = analysisSessionId;
                // 触发change事件加载详情
                await loadThreatDetailsForSession();
            }
        } catch (error) {
            console.error('❌ 切换到威胁详情页面失败:', error);
            showToast('切换到威胁详情页面失败', 'error');
        }
    }, 100);
}

// 下载威胁报告
async function downloadThreatReport(analysisSessionId) {
    try {
        showToast('正在生成威胁报告...', 'info');
        
        const response = await fetch(`${API_BASE}/threats/${analysisSessionId}`);
        const data = await response.json();
        
        if (data.success) {
            // 生成报告内容
            const reportContent = generateThreatReportContent(data);
            
            // 创建并下载文件
            const blob = new Blob([reportContent], { type: 'text/plain;charset=utf-8' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `威胁分析报告_${data.session_info.enterprise_name}_${analysisSessionId.substring(0, 8)}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            
            showToast('威胁报告下载完成', 'success');
        } else {
            showToast('生成威胁报告失败', 'error');
        }
    } catch (error) {
        console.error('❌ 下载威胁报告失败:', error);
        showToast('下载威胁报告失败', 'error');
    }
}

// 生成威胁报告内容
function generateThreatReportContent(data) {
    const session = data.session_info;
    const threats = data.threat_details;
    const stats = data.statistics;
    
    let content = `企业威胁分析报告
====================

企业信息:
- 企业名称: ${session.enterprise_name}
- 分析会话ID: ${session.analysis_session_id}
- 原始会话ID: ${session.original_session_id}
- 分析开始时间: ${formatTime(session.analysis_started_at)}
- 分析完成时间: ${formatTime(session.analysis_completed_at)}
- 分析状态: ${getStatusText(session.status)}

统计概览:
- 总分析数量: ${stats.total_analyzed}
- 检测威胁数量: ${stats.total_threats}
- 平均威胁评分: ${stats.avg_score}
- 最高威胁评分: ${stats.max_score}
- 平均置信度: ${stats.avg_confidence}

威胁等级分布:
- 严重威胁: ${stats.critical_count}
- 高危威胁: ${stats.high_count}
- 中危威胁: ${stats.medium_count}
- 低危威胁: ${stats.low_count}

详细威胁列表:
====================

`;

    threats.forEach((threat, index) => {
        if (threat.threat_detected) {
            content += `威胁 #${index + 1}
---------
问题: ${threat.question_text}
AI回答: ${threat.ai_response}
威胁等级: ${threat.threat_level}
威胁评分: ${threat.threat_score}/10
置信度: ${threat.confidence_score}
威胁描述: ${threat.threat_description || '无'}
威胁类型: ${threat.threat_types.join(', ') || '无'}
建议措施: ${threat.recommended_actions.join('; ') || '无'}
AI提供商: ${threat.ai_provider}
分析时间: ${formatTime(threat.analyzed_at)}

`;
        }
    });

    content += `
报告生成时间: ${formatTime(new Date().toISOString())}
`;

    return content;
}



// ==================== 威胁详情管理页面功能 ====================

// 全局变量存储当前威胁详情数据
let currentThreatDetails = [];
let filteredThreatDetails = [];

// 加载威胁分析统计数据（用于威胁监控页面）
async function loadThreatStatistics() {
    try {
        const response = await fetch(`${API_BASE}/threats/statistics`);
        const data = await response.json();
        
        if (data.success) {
            updateThreatStats(data.overall_stats);
            updateThreatLevelDistribution(data.threat_level_distribution);
            updateEnterpriseRankings(data.enterprise_rankings);
        } else {
            console.error('❌ 加载威胁统计失败:', data.error);
            showToast('加载威胁统计失败', 'error');
        }
    } catch (error) {
        console.error('❌ 威胁统计请求失败:', error);
        showToast('威胁统计请求失败', 'error');
    }
}

// 更新威胁统计数据
function updateThreatStats(stats) {
    document.getElementById('threat-total-sessions').textContent = stats.total_sessions || 0;
    document.getElementById('threat-total-enterprises').textContent = stats.total_enterprises || 0;
    document.getElementById('threat-total-threats').textContent = stats.total_threats || 0;
    document.getElementById('threat-avg-score').textContent = stats.overall_avg_score || '0.0';
    
    animateNumbers();
}

// 更新威胁等级分布
function updateThreatLevelDistribution(distribution) {
    document.getElementById('critical-count').textContent = distribution.critical || 0;
    document.getElementById('high-count').textContent = distribution.high || 0;
    document.getElementById('medium-count').textContent = distribution.medium || 0;
    document.getElementById('low-count').textContent = distribution.low || 0;
}

// 更新企业风险排名
function updateEnterpriseRankings(rankings) {
    const container = document.getElementById('enterprise-rankings');
    
    if (!rankings || rankings.length === 0) {
        container.innerHTML = '<div class="empty-state">暂无企业风险数据</div>';
        return;
    }
    
    const html = rankings.map((enterprise, index) => `
        <div class="enterprise-ranking-item">
            <div class="ranking-info">
                <div class="enterprise-name">${index + 1}. ${enterprise.enterprise_name}</div>
                <div class="enterprise-stats">
                    ${enterprise.session_count} 次分析 • ${enterprise.total_threats} 个威胁
                </div>
            </div>
            <div class="threat-score">
                ${enterprise.avg_score}
                <span class="threat-level-badge ${enterprise.max_level}">${enterprise.max_level}</span>
            </div>
        </div>
    `).join('');
    
    container.innerHTML = html;
}

// 加载威胁分析会话列表（用于威胁监控页面）
async function loadThreatSessionsForThreats() {
    const loadingEl = document.getElementById('threats-sessions-loading');
    const listEl = document.getElementById('threats-sessions-list');
    
    // 显示加载状态
    loadingEl.style.display = 'flex';
    listEl.innerHTML = '';
    
    try {
        const response = await fetch(`${API_BASE}/threats?limit=50`);
        const data = await response.json();
        
        if (data.success) {
            displayThreatSessionsForThreats(data.threat_sessions);
        } else {
            console.error('❌ 加载威胁会话失败:', data.error);
            showToast('加载威胁会话失败', 'error');
            listEl.innerHTML = '<div class="empty-state">加载失败</div>';
        }
    } catch (error) {
        console.error('❌ 威胁会话请求失败:', error);
        showToast('威胁会话请求失败', 'error');
        listEl.innerHTML = '<div class="empty-state">请求失败</div>';
    } finally {
        loadingEl.style.display = 'none';
    }
}

// 显示威胁分析会话（用于威胁监控页面）
function displayThreatSessionsForThreats(sessions) {
    const container = document.getElementById('threats-sessions-list');
    
    if (!sessions || sessions.length === 0) {
        container.innerHTML = '<div class="empty-state">暂无威胁分析数据</div>';
        return;
    }
    
    const html = `
        <table class="threat-sessions-table">
            <thead>
                <tr>
                    <th>企业名称</th>
                    <th>分析时间</th>
                    <th>分析项目</th>
                    <th>威胁检测</th>
                    <th>威胁等级</th>
                    <th>平均评分</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${sessions.map(session => `
                    <tr>
                        <td>
                            <strong>${session.enterprise_name}</strong>
                        </td>
                        <td>${formatTime(session.analysis_started_at)}</td>
                        <td>${session.total_responses || 0}</td>
                        <td>
                            <span style="color: ${session.threats_detected > 0 ? '#dc2626' : '#16a34a'};">
                                ${session.threats_detected || 0}
                            </span>
                        </td>
                        <td>
                            ${session.highest_threat_level ? 
                                `<span class="threat-level-badge ${session.highest_threat_level}">${session.highest_threat_level}</span>` : 
                                '<span class="threat-level-badge low">无</span>'
                            }
                        </td>
                        <td>
                            <strong style="color: var(--accent-400);">${session.avg_threat_score}</strong>
                        </td>
                        <td>
                            <span class="status-badge ${session.status}">${getStatusText(session.status)}</span>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="viewThreatDetails('${session.analysis_session_id}')">
                                <i class="fas fa-eye"></i>
                                查看详情
                            </button>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    
    container.innerHTML = html;
}

// 加载威胁分析会话列表（为详情页面）
async function loadThreatSessionsForDetails() {
    try {
        const response = await fetch(`${API_BASE}/threats?limit=100`);
        const data = await response.json();
        
        if (data.success) {
            const selector = document.getElementById('threat-session-selector');
            selector.innerHTML = '<option value="">请选择威胁分析会话...</option>';
            
            data.threat_sessions.forEach(session => {
                const option = document.createElement('option');
                option.value = session.analysis_session_id;
                option.textContent = `${session.enterprise_name} - ${formatTime(session.analysis_started_at)} (${session.threats_detected}个威胁)`;
                selector.appendChild(option);
            });
            
            showToast('威胁会话列表已更新', 'success');
        } else {
            showToast('加载威胁会话失败', 'error');
        }
    } catch (error) {
        console.error('❌ 加载威胁会话失败:', error);
        showToast('加载威胁会话失败', 'error');
    }
}

// 加载指定会话的威胁详情
async function loadThreatDetailsForSession() {
    const sessionId = document.getElementById('threat-session-selector').value;
    const infoDiv = document.getElementById('selected-session-info');
    const containerDiv = document.getElementById('threat-details-container');
    
    if (!sessionId) {
        infoDiv.style.display = 'none';
        containerDiv.style.display = 'none';
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/threats/${sessionId}`);
        const data = await response.json();
        
        if (data.success) {
            // 显示会话信息
            const infoText = document.getElementById('session-info-text');
            infoText.innerHTML = `
                <strong>企业:</strong> ${data.session_info.enterprise_name} |
                <strong>分析时间:</strong> ${formatTime(data.session_info.analysis_started_at)} |
                <strong>威胁数量:</strong> ${data.session_info.threats_detected} |
                <strong>最高等级:</strong> ${data.session_info.highest_threat_level || '无'}
            `;
            infoDiv.style.display = 'block';
            
            // 存储威胁详情数据
            currentThreatDetails = data.threat_details;
            filteredThreatDetails = [...currentThreatDetails];
            
            // 显示威胁详情列表
            displayThreatDetailsList(filteredThreatDetails);
            containerDiv.style.display = 'block';
            
        } else {
            showToast('加载威胁详情失败', 'error');
        }
    } catch (error) {
        console.error('❌ 威胁详情请求失败:', error);
        showToast('威胁详情请求失败', 'error');
    }
}

// 显示威胁详情列表
function displayThreatDetailsList(threatDetails) {
    const container = document.getElementById('threat-details-list');
    const countBadge = document.getElementById('threat-count-badge');
    
    countBadge.textContent = `${threatDetails.length} 项威胁`;
    
    if (threatDetails.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-search"></i>
                <h3>无匹配的威胁数据</h3>
                <p>请调整筛选条件或选择其他会话</p>
            </div>
        `;
        return;
    }
    
    const html = threatDetails.map((threat, index) => `
        <div class="threat-detail-card ${threat.threat_detected ? 'has-threat' : 'no-threat'}" onclick="showThreatDetailModal(${index})">
            <div class="threat-card-header">
                <div class="threat-card-title">
                    <span class="threat-index">#${index + 1}</span>
                    <span class="threat-level-badge ${threat.threat_level}">${threat.threat_level}</span>
                    <span class="threat-score">评分: ${threat.threat_score}</span>
                </div>
                <div class="threat-status ${threat.threat_detected ? 'detected' : 'safe'}">
                    <i class="fas ${threat.threat_detected ? 'fa-exclamation-triangle' : 'fa-check-circle'}"></i>
                    ${threat.threat_detected ? '威胁检测' : '安全'}
                </div>
            </div>
            <div class="threat-card-body">
                <div class="threat-question">
                    <strong>问题:</strong> ${threat.question_text.substring(0, 100)}${threat.question_text.length > 100 ? '...' : ''}
                </div>
                <div class="threat-response">
                    <strong>AI回答:</strong> ${threat.ai_response.substring(0, 150)}${threat.ai_response.length > 150 ? '...' : ''}
                </div>
                ${threat.threat_detected ? `
                    <div class="threat-description">
                        <strong>威胁描述:</strong> ${threat.threat_description || '无'}
                    </div>
                ` : ''}
                <div class="threat-meta">
                    <span><i class="fas fa-robot"></i> ${threat.ai_provider}</span>
                    <span><i class="fas fa-clock"></i> ${formatTime(threat.analyzed_at)}</span>
                    <span><i class="fas fa-percentage"></i> 置信度: ${threat.confidence_score}</span>
                </div>
            </div>
        </div>
    `).join('');
    
    container.innerHTML = html;
}

// 显示威胁详情模态框
function showThreatDetailModal(index) {
    const threat = filteredThreatDetails[index];
    
    const modalHtml = `
        <div class="modal-overlay" onclick="closeModal()">
            <div class="modal-content large" onclick="event.stopPropagation()">
                <div class="modal-header">
                    <h2><i class="fas fa-shield-alt"></i> 威胁详情 #${index + 1}</h2>
                    <button class="modal-close" onclick="closeModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="threat-detail-full">
                        <div class="threat-overview">
                            <div class="threat-badges">
                                <span class="threat-level-badge ${threat.threat_level}">${threat.threat_level}</span>
                                <span class="threat-score-badge">评分: ${threat.threat_score}/10</span>
                                <span class="confidence-badge">置信度: ${threat.confidence_score}</span>
                                <span class="status-badge ${threat.threat_detected ? 'detected' : 'safe'}">
                                    ${threat.threat_detected ? '威胁检测' : '安全'}
                                </span>
                            </div>
                            <div class="threat-meta-info">
                                <div><strong>AI提供商:</strong> ${threat.ai_provider}</div>
                                <div><strong>分析时间:</strong> ${formatTime(threat.analyzed_at)}</div>
                            </div>
                        </div>
                        
                        <div class="threat-content-full">
                            <div class="content-section">
                                <h4><i class="fas fa-question-circle"></i> 分析问题</h4>
                                <p>${threat.question_text}</p>
                            </div>
                            
                            <div class="content-section">
                                <h4><i class="fas fa-robot"></i> AI回答</h4>
                                <div class="ai-response-full">${threat.ai_response}</div>
                            </div>
                            
                            ${threat.threat_detected ? `
                                <div class="content-section">
                                    <h4><i class="fas fa-exclamation-triangle"></i> 威胁描述</h4>
                                    <p>${threat.threat_description || '无具体描述'}</p>
                                </div>
                                
                                ${threat.threat_types.length > 0 ? `
                                    <div class="content-section">
                                        <h4><i class="fas fa-tags"></i> 威胁类型</h4>
                                        <div class="threat-types">
                                            ${threat.threat_types.map(type => `<span class="threat-type-tag">${type}</span>`).join('')}
                                        </div>
                                    </div>
                                ` : ''}
                                
                                ${threat.recommended_actions.length > 0 ? `
                                    <div class="content-section">
                                        <h4><i class="fas fa-lightbulb"></i> 建议措施</h4>
                                        <ul class="recommended-actions">
                                            ${threat.recommended_actions.map(action => `<li>${action}</li>`).join('')}
                                        </ul>
                                    </div>
                                ` : ''}
                            ` : ''}
                            
                            ${threat.analysis_details && Object.keys(threat.analysis_details).length > 0 ? `
                                <div class="content-section">
                                    <h4><i class="fas fa-info-circle"></i> 分析详情</h4>
                                    <pre class="analysis-details">${JSON.stringify(threat.analysis_details, null, 2)}</pre>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                    <button class="btn btn-primary" onclick="exportSingleThreat(${index})">
                        <i class="fas fa-download"></i> 导出此威胁
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', modalHtml);
}

// 筛选威胁详情
function filterThreatDetails() {
    const levelFilter = document.getElementById('level-filter').value;
    const detectionFilter = document.getElementById('detection-filter').value;
    const scoreFilter = document.getElementById('score-filter').value;
    
    filteredThreatDetails = currentThreatDetails.filter(threat => {
        // 威胁等级筛选
        if (levelFilter && threat.threat_level !== levelFilter) {
            return false;
        }
        
        // 威胁检测筛选
        if (detectionFilter !== '') {
            const isDetected = detectionFilter === 'true';
            if (threat.threat_detected !== isDetected) {
                return false;
            }
        }
        
        // 评分范围筛选
        if (scoreFilter) {
            const score = threat.threat_score;
            switch (scoreFilter) {
                case '8-10':
                    if (score < 8) return false;
                    break;
                case '6-8':
                    if (score < 6 || score >= 8) return false;
                    break;
                case '0-6':
                    if (score >= 6) return false;
                    break;
            }
        }
        
        return true;
    });
    
    displayThreatDetailsList(filteredThreatDetails);
}

// 导出威胁详情
function exportThreatDetails() {
    const sessionId = document.getElementById('threat-session-selector').value;
    if (!sessionId) {
        showToast('请先选择威胁分析会话', 'warning');
        return;
    }
    
    downloadThreatReport(sessionId);
}

// 导出单个威胁
function exportSingleThreat(index) {
    const threat = filteredThreatDetails[index];
    
    const content = `威胁详情报告
================================

威胁等级: ${threat.threat_level.toUpperCase()}
威胁评分: ${threat.threat_score}/10
置信度: ${threat.confidence_score}
AI提供商: ${threat.ai_provider}
分析时间: ${formatTime(threat.analyzed_at)}
威胁状态: ${threat.threat_detected ? '已检测' : '安全'}

问题:
${threat.question_text}

AI回答:
${threat.ai_response}

${threat.threat_detected ? `
威胁描述:
${threat.threat_description || '无具体描述'}

威胁类型: ${threat.threat_types.join(', ') || '无'}

${threat.recommended_actions.length > 0 ? `
建议措施:
${threat.recommended_actions.map(action => `- ${action}`).join('\n')}
` : ''}
` : ''}

导出时间: ${new Date().toLocaleString()}
`;
    
    downloadFile(`威胁详情_${index + 1}_${new Date().toISOString().slice(0, 10)}.txt`, content);
    showToast('威胁详情导出成功', 'success');
    closeModal();
}



console.log('✅ 前端应用初始化完成');